package org.example.springboot.component;

import lombok.extern.slf4j.Slf4j;
import org.example.springboot.vo.SseDto;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * SseEmitterServer
 *
 * @author fz
 * 2024/3/26 11:20
 **/
@Slf4j
@Component
public class SseEmitterServer {
    // 用于存储所有连接的客户端
    private final CopyOnWriteArrayList<SseEmitter> clients = new CopyOnWriteArrayList<>();

    /**
     * 客户端连接 SSE 端点
     *
     * @return SseEmitter
     */
    public SseEmitter connect() {
        SseEmitter emitter = new SseEmitter(0L);
        clients.add(emitter);

        // 移除断开的连接
        emitter.onCompletion(() -> clients.remove(emitter));
        emitter.onTimeout(() -> clients.remove(emitter));

        return emitter;
    }

    /**
     * 向所有客户端广播消息
     *
     * @param message 消息内容
     * @return 通知结果
     */
    public String broadcast(@RequestParam String message) {
        clients.forEach(emitter -> {
            try {
                emitter.send(SseEmitter.event().data(message));
            } catch (Exception e) {
                clients.remove(emitter); // 移除不可用的连接
            }
        });
        return "消息广播到 " + clients.size() + " 客户端";
    }

}